#include "stdafx.h"
#include "ThreeDimensionView.h"

ThreeDimensionView::ThreeDimensionView(QWidget *parent)
	: QGLWidget(parent)
{
	this->sketchModel = NULL;
	this->trackball   = new CTrackball();
	this->lighting    = new CLighting();
	xpos = 0; ypos = 0; zpos = 0; xrot = 0; yrot = 0; angle=0.0;
	camDist = 5;
	fov = 8.0;
}

ThreeDimensionView::~ThreeDimensionView()
{

}

void ThreeDimensionView::loadSketchModel(SketchModel *model)
{
	this->sketchModel = model;
	this->sketchModel->initialize3D();
}

void ThreeDimensionView::initializeGL()
{
	makeCurrent();	
	if (this->sketchModel != NULL)
		this->sketchModel->initialize3D();

	// select clearing color (for glClear)
	glClearColor (1,1,1,1);	// RGB-value for white
	// enable depth buffering
	glEnable(GL_DEPTH_TEST);
	// initialize view (simple orthographic projection)
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(fov, 1, 0.1, 1000);
	
	trackball->tbInit(GLUT_LEFT_BUTTON);
	
	// enable shading and lighting
	lighting->enable();
	glShadeModel(GL_SMOOTH);
}

void ThreeDimensionView::paintGL()
{
	makeCurrent();
	glClearColor( 1, 1, 1, 1);
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

	glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
	setCamera();
	trackball->tbMatrix();
	glTranslatef(0.0, -0.5*(float)sketchModel->getHeight()/height(), 0.0);

	if (this->sketchModel != NULL)
		this->sketchModel->render3D();

	glFlush();
}

void ThreeDimensionView::resizeGL(int w, int h)
{
	glViewport(0, 0, (GLsizei) w, (GLsizei) h);
	trackball->tbReshape(w, h);
}

void ThreeDimensionView::setCamera()
{
	glRotatef(xrot,1.0,0.0,0.0);
	glRotatef(yrot,0.0,1.0,0.0);
	glTranslated(-xpos, -ypos, -zpos-camDist);
	gluLookAt(0, 0, camDist, 0,0,0, 0,1,0);
}

void ThreeDimensionView::mouseMoveEvent(QMouseEvent *event)
{
	trackball->tbMotion(event->x(), event->y());
	updateGL();
}

void ThreeDimensionView::mousePressEvent(QMouseEvent *event)
{
	Qt::MouseButton button = event->button();
	if (button == Qt::LeftButton)
		trackball->tbMouse(GLUT_LEFT_BUTTON, GLUT_DOWN, event->x(), event->y());
	updateGL();
}

void ThreeDimensionView::mouseReleaseEvent(QMouseEvent *event)
{
	Qt::MouseButton button = event->button();
	if (button == Qt::LeftButton)
		trackball->tbMouse(GLUT_LEFT_BUTTON, GLUT_UP, event->x(), event->y());
	updateGL();
}

void ThreeDimensionView::wheelEvent(QWheelEvent *event)
{
	int numDegrees = event->delta()/8;
	int numSteps   = numDegrees / 10;

	fov += -numSteps;
	if (fov < 1)
		fov = 1;
	else if (fov > 50)
		fov = 50;

	this->makeCurrent();
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(fov, 1, 0.1, 1000);

	updateGL();
}